const cartModule = {
    namespaced: true,    //开启了命名空间
    state: {
        cart: [],
    },
    getters: {
        // 商品数组
        cart: state => state.cart,
        // 全选状态
        checkAll: state => state.cart.every(item => item.state),
        // 购物车数组中一共有多少数据   (购物车按钮徽标显示)
        productNum: state => state.cart.length,
        // 被选中状态的商品计算总价
        totalPrice: state => state.cart.reduce((total, item) => {
            item.state ? total + (item.price * item.amount).toFixed(2) : total
        }, 0)

    },
    mutations: {
        /**
         * 添加商品到购物车
         * @param {*} state 
         * @param {*} payload {id,price,product,picture,amount}
         */
        addToCart(state, payload) {
            // 判断是否存在，有叠加，无置1
            const has = state.cart.some(prod => prod.id === payload.id)
            if (has) { // 存在，则叠加数量
                state.cart = state.cart.map(prod => {
                    const copy = { ...prod }
                    if (copy.id === payload.id) {
                        copy.amount += payload.amount || 1
                    }
                    return copy
                })
            } else { // 不存在，添加到数组中，每一项添加 state 属性表示是否选中
                state.cart.push({ ...payload, amount: 1, state: false })
            }
        },
        /**
         * 移除商品
         * @param {*} state 
         * @param {*} payload {id }
         */
        removeFromCart(state, id) {
            state.cart = state.cart.filter(item => item.id != id)
        },
        /**
         * 切换选中状态
         * @param {*} state 
         * @param {*} id {id}
         * 
         */
        changeOne(state, id) {
            state.cart.forEach(item => {
                if (item.id == id) {
                    item.state = !item.state;
                }
            })
        },
        /**
         * 切换全选状态
         * @param {*} state 
         * @param {*} checkAll {checkAll}
         */
        changeAll(state, checkAll) {
            checkAll = !checkAll
            state.cart.map(item => item.state = checkAll)
        }
    },
}
export default cartModule